

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <memory>

#include "InetAddr.hpp"
#include"Log.hpp"
#include"Socket.hpp"

using namespace socket_ns;
class TcpServer;
using http_t = std::function<std::string(std::string reqeust)>;
class ThreadData
{
    public:
    ThreadData(socket_sptr fd,InetAddr addr,TcpServer *s)
    :sockfd(fd),
    clientaddr(addr),
    self(s)
    {}
    public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};
class TcpServer
{
    public:
    TcpServer(int port,http_t service)
    :_localaddr("0",port),
    _listensock(std::make_unique<TcpSocket>()),
     _http_service(service),
     _isrunning(false)
    {
            _listensock->BuildListenSocket(_localaddr);
    }
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());//获取条用线程标识符(ID)
        ThreadData *td = static_cast<ThreadData*>(args);
        std::string request,response;
        //大概率是一个完整的http
        ssize_t n = td->sockfd->Recv(&request);
        if(n>0)
        {
            response =td->self->_http_service(request);
            td->sockfd->Send(response);//发送应答
        }
        td->sockfd->Close();
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr peeraddr;
           socket_sptr normalsock = _listensock->Accepter(&peeraddr);
            if(normalsock==nullptr)
            continue;
            
            pthread_t t;
            ThreadData *td = new ThreadData(normalsock,peeraddr,this);
            pthread_create(&t,nullptr,HandlerSock,td);//线程分离
        }
        _isrunning = false; 
    }
    ~TcpServer()
    {}
    private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    http_t _http_service;
};